// import __config from '../etc/config.js'

//获取年月日时分秒/
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//获取年月日时分秒-
const formatTime1 = date => {
    var myDate = new Date();
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = myDate.getHours()
    const minute = myDate.getMinutes()
    const second = myDate.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//获取时分秒
const formatTime3 = date => {
    var myDate = new Date();

    const hour = myDate.getHours()
    const minute = myDate.getMinutes()
    const second = myDate.getSeconds()

    return [hour, minute, second].map(formatNumber).join(':')
}
//获取年月日-
const formatTime4 = date => {
     const mydate = new Date(date)
    const year = mydate.getFullYear()
    const month = mydate.getMonth() + 1
    const day = mydate.getDate()
    return [year, month, day].map(formatNumber).join('-')
}
const formatTime5 = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(formatNumber).join('')
}
const formatTime6 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  // const day = date.getDate()
  return [year, month].map(formatNumber).join('')
}
//获取时分秒
const formatTime7 = date => {
    const myDate = new Date(date)
    const hour = myDate.getHours()
    const minute = myDate.getMinutes()

    return [hour, minute].map(formatNumber).join(':')
}
// 转换时间戳函数
const timestampToTime1 = date => {
    // var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = '01 00:00:00';
    return Y + M + D;
    // var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    // var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    // var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    // return Y + M + D + h + m + s;
}
/**utils\util.jsD:\XJDXX\A待上线前端\Xjd\utils\util.js
 * 删除数组中的某一个对象
 * @param arr {Array} 数组
 * @param obj {Object} 需要删除的对象
 * @returns {Array} 处理之后的数组
 */
const arrRemoveObj = (arr, obj) => {
    let len = arr.length;
    for (let i = 0; i < len; i++) {
        if (arr[i] === obj) {
            if (i === 0) {
                arr.shift();
                return arr;
            } else if (i === len - 1) {
                arr.pop();
                return arr;
            } else {
                arr.splice(i, 1);
                return arr;
            }
        }
    }
};
//判断当前时间是否在该范围内
const checkAuditTime = (beginDate, endDate) => {
    var beginDate1 = new Date(beginDate);
    var endDate1 = new Date(endDate);
    var nowDate = new Date();
    return nowDate.getTime() - beginDate1.getTime() >= 0 && nowDate.getTime() <= endDate1.getTime();
};
// 获取今日开始时间（0点0分0秒）
const getTodayStart = () => {
  const date = new Date();
  date.setHours(0, 0, 0, 0); // 时间归零
  return formatDateTime(date);
};
// 获取今日开始时间（0点0分0秒）
const getStart = (date) => {
  // const date = new Date();
  date.setHours(0, 0, 0, 0); // 时间归零
  return formatDateTime(date);
};
const getEnd = (date) => {
  // const date = new Date();
  date.setHours(59, 59, 59, 999); // 时间归零
  return formatDateTime(date);
};
//判断一个字符串是否仅包含数字
function isNumeric(str) {
    return /^\d+$/.test(str);
}
// 时间格式化函数（生成 YYYY-MM-DD HH:mm:ss 格式）
const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
//分转化为元 - 正则解决
const regFenToYuan = (fen) => {
    var num = fen;
    num = fen * 0.01;
    num += '';
    var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
    num = num.replace(reg, '$1');
    num = parseFloat(num)
    return num
};
//元转分 - 解决精度问题 yuan:要转换的钱，单位元； digit：转换倍数
const regYuanToFen = (yuan, digit) => {
    var m = 0,
        s1 = yuan.toString(),
        s2 = digit.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
const GetCombination2 = function (list, t, n, m, b, M) {
    for (var i = n; i >= m; i--) {
        b[m - 1] = i - 1;
        if (m > 1) {
            GetCombination2(list, t, i - 1, m - 1, b, M);
        }
        else {
            if (list == null) {
                list = [];
            }
            var temp = [];
            for (var j = 0; j < b.length; j++) {
                temp[j] = t[b[j]];
            }
            list.push(temp);
        }
    }
};
var GetCombination1 = function (t, n) {
    if (t.Length < n) {
        return null;
    }
    var temp = [];
    var list = [];
    GetCombination2(list, t, t.length, n, temp, n);
    return list;
};
/**
 * 组合多个数组
 * @param  {...Array} arrays 
 * @returns 
 */
const combine = function combine(arrays) {
    let list = [];
    let helper = function (index, prev) {
        // 当前数组
        let array = arrays[index];
        // 是否为最后一个数组
        let is_last = arrays.length - 1 == index;
        for (let item of array) {
            let current = prev.concat(item);
            if (is_last) {
                list.push(current);
            } else {
                helper(index + 1, current);
            }
        }
    };

    helper(0, []);

    return list;
}
// let names = ['iPhone X', 'iPhone XS'];
// let colors = ['黑色', '白色'];
// let storages = ['64g', '256g'];
// console.log(combine(names, colors, storages));

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
};
const get = (url, query) => {
    const contentType = query ? "application/x-www-form-urlencoded" : "application/json",
        data = query || {};
    return new Promise((resolve, reject) => {
        wx.request({
            url: __config.localUrl + url,
            // url: "https://jzm.xjdio.com/" + url,
            //  url: "https://house.xjdxx.cn/" + url,
            data,
            header: {
                'content-type': contentType
            },
            success: (res) => {
                const data = res.data;
                if (data.success == true) {
                    wx.showToast({
                        title: '成功',
                        icon: 'success',
                        duration: 100
                    })
                    resolve(data)
                } else
                    if (data.success == false) {
                        wx.showToast({
                            title: data.errorMessage,
                            icon: 'false',
                            duration: 100
                        })
                        resolve(data)
                    }
            },
            fail: (res) => {
                reject(res)
                wx.showToast({
                    title: '网络错误',
                })
            }
        })
    })
}

const calcDescartes = function calcDescartes(array) {
    if (array.length < 2) return array[0] || [];
    return [].reduce.call(array, function (col, set) {
        var res = [];
        let arraylength = array.length;
        //let collength = col.length - 1;
        col.forEach(function (c, j) {
            set.forEach(function (s, i) {
                var t = [].concat(Array.isArray(c) ? c : [c]);
                t.push(s);
                if (t.length == arraylength) {
                    t.push({ id: 1, name: "价格", price: '1' });
                    t.push({ id: 2, name: "库存", stocks: '1' });
                    t.push({ id: 3, name: "是否启用", enable: false });
                    // t.push([{ id: 4, images: null, imagesPreview: '/img/audit-3.png' }]);
                    t.push({ imagelist: [{ id: 4, images: null, imagesPreview: null },] });
                }
                res.push(t);
            })
        });

        return res;
    });
}
const post = (url, data) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: __config.localUrl + url,
            method: "POST",
            data,
            success: (res) => {
                const data = res.data;
                if (data.success == true) {
                    wx.showToast({
                        title: '成功',
                        icon: 'success',
                        duration: 100
                    })
                    resolve(data)
                } else
                    if (data.success == false) {
                        wx.showToast({
                            title: '失败:' + data.errorMessage,
                            icon: 'false',
                            duration: 500
                        })
                        resolve(data)
                    }
            },
            fail: (res) => {
                reject(res)
                wx.showToast({
                    title: '网络错误',
                    icon: 'false',
                    duration: 500
                })
            }
        })
    })
}
const postPrepayid = (url, data) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: __config.localUrl + url,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data,
            success: (res) => {
                const data = res.data;
                if (data.success == true) {
                    wx.showToast({
                        title: '成功',
                        icon: 'success',
                        duration: 100
                    })
                    resolve(data)
                } else
                    if (data.success == false) {
                        wx.showToast({
                            title: '失败:' + data.errorMessage,
                            icon: 'false',
                            duration: 500
                        })
                        resolve(data)
                    }
            },
            fail: (res) => {
                reject(res)
                wx.showToast({
                    title: '网络错误',
                    icon: 'false',
                    duration: 500
                })
            }
        })
    })
}
const put = (url, data) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: __config.localUrl + url,
            //url: "https://jzm.xjdio.com/" + url,
            //  url: "https://house.xjdxx.cn/" + url,
            method: "PUT",
            data,
            success: (res) => {
                const data = res.data;
                if (data.success == true) {
                    wx.showToast({
                        title: data.errorMessage,
                        icon: 'success',
                        duration: 100
                    })
                    resolve(data)
                } else
                    if (data.success == false) {
                        wx.showToast({
                            title: '失败:' + data.errorMessage,
                            icon: 'false',
                            duration: 500
                        })
                        resolve(data)
                    }
            },
            fail: (res) => {

                reject('失败')
                wx.showToast({
                    title: '网络错误',
                    icon: 'false',
                    duration: 500
                })
            }
        })
    })
}
const Delete = (url, data) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: __config.localUrl + url,
            //url: "https://jzm.xjdio.com/" + url,
            //  url: "https://house.xjdxx.cn/" + url,
            method: "DELETE",
            data,
            success: (res) => {
                const data = res.data;
                if (data.success == true) {
                    wx.showToast({
                        title: data.errorMessage,
                        icon: 'success',
                        duration: 100
                    })
                    resolve(data)
                } else
                    if (data.success == false) {
                        wx.showToast({
                            title: '失败:' + data.errorMessage,
                            icon: 'false',
                            duration: 500
                        })
                        resolve(data)
                    }
            },
            fail: (res) => {
                reject(res)
                wx.showToast({
                    title: '网络错误',
                    icon: 'false',
                    duration: 500
                })
            }
        })
    })
}
const getUrl = function getUrl(str, data) {
    //获取“=”的下标
    var url = data;

    //var mycount=this.getCharCount(str,',');
    while (str.indexOf('https') != -1) {
        var myobj = {};
        // let myvalue = null;
        let myindex = str.indexOf(',');
        if ((myindex != -1)) {
            myobj.dsUrl = str.split(",")[0];
            url.push(myobj);
            str = str.substr(str.indexOf(',') + 1);
        } else {
            myobj.dsUrl = str;
            url.push(myobj);
            return url;
        }
    }
    return url;
}
const getUrl1 = function getUrl1(str, str1, data) {
    //获取“=”的下标
    var url = data;
    //var mycount=this.getCharCount(str,',');
    while (str.indexOf('https') != -1 && str1.indexOf('https') != -1) {
        var myobj = {};
        // let myvalue = null;
        let myindex = str.indexOf(',');
        let myindex1 = str1.indexOf(',');
        if (myindex != -1 && myindex1 != -1) {
            myobj.images = str.split(",")[0];
            myobj.imagesPreview = str1.split(",")[0];
            url.push(myobj);
            str = str.substr(str.indexOf(',') + 1);
            str1 = str1.substr(str1.indexOf(',') + 1);
        } else {
            myobj.images = str;
            myobj.imagesPreview = str1;
            url.push(myobj);
            url.push({ images: null, imagesPreview: null });
            return url;
        }
    }
    url.push({ images: null, imagesPreview: null });
    return url;
}
const uploadfile = (url, data) => {
    let myimg = null,
        myurl = null;
    myimg = url.split(',')[0];
    myurl = url.split(',')[1];
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: __config.localUrl + myurl,
            filePath: myimg,//'http://192.168.10.175:8181/upload/PicUrl/8011D0BB-0B47-EF0C-B319-85F58FE6B9B1/eSSOa0P9gBai9ac222eedbc0ba843369735a635f6152.png',//res.tempFilePaths[0],//要上传文件资源的路径
            name: 'Xjd', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
            formData: data,
            method: 'POST',
            header: {
                'content-type': 'multipart/form-data' // 默认值
            },
            success: function (res) {

                const mydata = JSON.parse(res.data)
                if (mydata.success) {
                    // tempimages.push(mydata);
                    resolve(mydata)
                }
            },
            fail: function (e) {

            },
            complete: function (res) {

            }
        })
    })
}

const booksStateTabel = (state) => {
    var result = [];
    switch (state) {
        case "0":
            result = {
                name: "已预约",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已预约",
                desc: "",
                btn: ""
            }
            break;
        case "1":
            result = {
                name: "已完成",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已完成",
                desc: "",
                btn: ""
            }
            break;
        case "2":
            result = {
                name: "施工中",
                icon: "/img/order/orderdetail-1.png",
                title: "施工中",
                desc: "",
                btn: "施工结束"
            }
            break;
        default:
            result = {
                name: "已预约",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已预约",
                desc: "",
                btn: ""
            }
    }
    return result;
}
const booksStateTabel1 = (state) => {
    var result = [];
    switch (state) {
        case "0":
            result = {
                name: "已预约",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已预约",
                desc: "",
                btn: ""
            }
            break;
        case "1":
            result = {
                name: "已完成",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已完成",
                desc: "",
                btn: ""
            }
            break;
        case "2":
            result = {
                name: "待接单",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "待接单",
                desc: "",
                btn: "接单"
            }
            break;
        case "3":
            result = {
                name: "施工中",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "施工中",
                desc: "",
                btn: "施工结束"
            }
            break;
        default:
            result = {
                name: "已预约",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已预约",
                desc: "",
                btn: ""
            }
    }
    return result;
}
const goodsStateTabel = (state) => {
    var result = [];
    switch (state) {
        case "1":
            result = {
                name: "待付款",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "待付款",
                desc: "待付款",
                btn: "去支付"
            }
            break;
        case "2":
            result = {
                name: "待发货",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已付款待发货",
                desc: "已付款待发货",
                btn: ""
            }
            break;
        case "3":
            result = {
                name: "已发货",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "已发货",
                desc: "已发货，等待确认收货",
                btn: "确认收货"
            }
            break;
        case "4":
            result = {
                name: "已收货",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                title: "订单完成",
                desc: "您可对本次服务进行评价",
                btn: "评价"
            }
            break;
        case "7":
            result = {
                name: "已取消",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-2.png",
                title: "订单关闭",
                desc: "",
                btn: ""
            }
            break;
        default:
            result = {
                name: "已完成",
                icon: "https://jzm.xjdio.com/images/order/orderdetail-2.png",
                title: "订单已完成",
                desc: "",
                btn: "评价"
            }
    }
    return result;
}
const stateTabel = (state, userFlag) => {
    var result = [];
    if (userFlag == 0) {//客户
        switch (state) {
            case "1":
                result = {
                    name: "已预约",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "预约成功",
                    desc: "正在为您分配服务人员",
                    btn: "取消订单"
                }
                break;
            case "2":
                result = {
                    name: "已分配",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "分配成功",
                    desc: "请等待服务人员与您联系",
                    btn: ""
                }
                break;
            case "3":
                result = {
                    name: "待付款",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "服务结束",
                    desc: "本次服务已完成，请支付",
                    btn: "去支付"
                }
                break;
            case "4":
                result = {
                    name: "已付款",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "订单完成",
                    desc: "您可对本次服务进行评价",
                    btn: "评价"
                }
                break;
            case "5":
                result = {
                    name: "已完成",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "订单完成",
                    desc: "您可对本次服务进行评价",
                    btn: "评价"
                }
                break;
            case "6":
                result = {
                    name: "已取消",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-2.png",
                    title: "订单关闭",
                    desc: "",
                    btn: ""
                }
                break;
            default:
                result = {
                    name: "已预约",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "预约成功",
                    desc: "正在为您分配服务人员",
                    btn: "取消订单"
                }
        }
    } else {
        switch (state) {
            case "1":
                result = {
                    name: "未派单",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "等未派单",
                    desc: "正在分配服务人员",
                    btn: ""
                }
                break;
            case "2":
                result = {
                    name: "待完成",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "正在施工",
                    desc: "请尽快与客户联系并完成本次服务",
                    btn: "施工结束"
                }
                break;
            case "3":
                result = {
                    name: "施工结束",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "施工完成，客户未付款",
                    desc: "本次服务已完成，等待客户付款",
                    btn: ""
                }
                break;
            case "4":
                result = {
                    name: "订单完成",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "施工完成，客户已付款",
                    desc: "本次服务已完成",
                    btn: ""
                }
                break;
            case "5":
                result = {
                    name: "订单完成",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "施工完成，客户已付款",
                    desc: "本次服务已完成",
                    btn: ""
                }
                break;
            case "6":
                result = {
                    name: "已取消",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-2.png",
                    title: "订单关闭",
                    desc: "",
                    btn: ""
                }
                break;
            default:
                result = {
                    name: "未派单",
                    icon: "https://jzm.xjdio.com/images/order/orderdetail-1.png",
                    title: "等未派单",
                    desc: "正在分配服务人员",
                    btn: ""
                }
        }
    }
    return result;
}
module.exports = {
    regFenToYuan,
    checkAuditTime,
    regYuanToFen,
    formatTime,
    formatTime1,
    formatTime3,
    formatTime4,
    formatTime5,
    formatTime6,
    formatTime7,
    timestampToTime1,
    formatNumber,
    get,
    post,
    postPrepayid,
    put,
    Delete,
    uploadfile,
    getUrl,
    getUrl1,
    goodsStateTabel,
    booksStateTabel,
    booksStateTabel1,
    arrRemoveObj: arrRemoveObj,
    stateTabel,
    GetCombination2,
    GetCombination1,
    calcDescartes,
    getTodayStart,
    formatDateTime,
    getStart,
    getEnd,
    isNumeric
}
